<template>
    <div id="exchange-candy">
      <!-- navbar -->
      <van-nav-bar @click-left="back" class="navbar">
        <template #left>
          <van-icon name="arrow-left" size="18" color="#f7f8fa" />
        </template>
        <template #right>
          <!--<span class="right-text" @click="onRightBtnClick">兑换记录</span>-->
        </template>
      </van-nav-bar>

      <!-- GST剩余 -->
      <van-cell-group style="margin-top: 10px">
        <van-cell>
          <template #default>
            <van-col span="24">
              <van-row>
                <van-col span="24" class="title">消耗GST</van-col>
                <van-col span="24" class="label">{{gst}}</van-col>
              </van-row>
            </van-col>
          </template>
        </van-cell>
      </van-cell-group>

      <!-- 兑换数量 -->
      <van-form @submit="onSubmit" style="margin-top: 10px">
        <van-field
          v-model="num"
          label="兑换数量"
          placeholder="请输入兑换数量"
          :formatter="formatter"
          type="digit"
          center
          clearable
        >
          <template #button>
            <van-button size="small" type="primary" class="btn" @click="fullExchange" plain>全部兑换</van-button>
          </template>
        </van-field>
      </van-form>

      <!-- 提交按钮 -->
      <van-tabbar v-model="active" active-color="#545c80">
        <van-tabbar-item @click="onClick">兑换</van-tabbar-item>
      </van-tabbar>

      <!-- 输入交易密码弹窗 -->
      <van-dialog
        v-model="show"
        title="交易密码"
        closeOnClickOverlay
        :showConfirmButton="false"
      >
        <!-- 密码输入框 -->
        <van-password-input
          class="password-input"
          :value="password"
          :focused="showKeyboard"
          @focus="showKeyboard = true"
        />
      </van-dialog>

      <!-- 数字键盘 -->
      <van-number-keyboard
        class="keyboard"
        :show="showKeyboard"
        @input="onInput"
        @delete="onDelete"
        @blur="showKeyboard = false"
      />

      <!-- 兑换记录 -->
      <van-popup v-model="store.state.exchangeCandy.showPopup" position="right" class="popup">
        <router-view/>
      </van-popup>
    </div>
</template>

<script>
  import store from '@/store'
  import axios from 'axios'
  import Vue from 'vue'
  import { Toast } from 'vant'

  Vue.use(Toast);

  export default {
    name: "ExchangeCandy",
    data() {
      return {
        gst: 0,                   // 消耗的GST数
        num: '',                  // 输入的兑换数量
        max: '',                  // 最大兑换数量
        active: 0,
        password: '',             // 交易密码
        show: false,              // 控制密码输入框展示
        showKeyboard: false,      // 控制数字键盘展示
        showPopup: false,         // 控制兑换记录展示
        store: store,
        user: JSON.parse(sessionStorage.getItem('user')), // 用户信息
      };
    },
    methods: {

      onSubmit() {

      },
      formatter(val) {
        // 输入的数超过最大兑换数
        if (val > this.max) {
          return this.max;
        }

        // 限制输入负数
        if (val == '-' || val <= 0) {
          return '';
        }

        return val;
      },
      // 全部兑换
      fullExchange() {
        this.num = this.max;
      },
      // 点击兑换按钮
      onClick() {
        if (this.num == '' || this.num === 0) {
          Toast({
            message: '请输入兑换数量',
            position: 'bottom',
          });
          return;
        }
        this.show = true;
        this.showKeyboard = true;
      },
      onInput(key) {
        this.password = (this.password + key).slice(0, 6);
      },
      onDelete() {
        this.password = this.password.slice(0, this.password.length - 1);
      },
      onRightBtnClick() {
        store.state.exchangeCandy.showPopup = true;
        this.$router.push('/exchange/candy/record');
      },
      updateCandy() { // 更新糖果数据
        axios.get(store.state.api + '/getInfoByUid', {
          params: {
            uid: this.user.uid,
          }
        }).then(res => {
          if (res.data.code == '200') {
            var pattern = /^\d*(?:\.\d{0,2})?/;
            var data = res.data.data;
            var user = {};

            user.candy = +data.candy.match(pattern)[0];       // 糖果
            user.contributionValue = data.contributionValue;  // 贡献值
            user.account = data.account;                      // 账号
            user.avatar = data.avatar;                        // 头像
            user.uid = data.uid;                              // 用户id
            user.nickname = data.nickName;                    // 用户昵称
            user.level = data.level;                          // 等级
            user.activity = data.activity;                    // 活跃度
            user.m_candy = +data.m_candy.match(pattern)[0];   // 交易市场糖果（GST）
            user.walletAddress = data.walletAddress;          // 钱包地址
            user.token = data.token;                          // 用户token

            sessionStorage.setItem('user', JSON.stringify(user));
            this.user = user;
            // 重新计算最大兑换数
            this.max = parseInt(this.user.m_candy);
          }
        }).catch(error => {

        });
      },
      back() {
        store.state.mine.showPopup = false;
        this.$router.back(-1);
      },
    },
    watch: {
      num: function (val, oldVal) {
        val = val === '' || val === '.' ? 0 : +val;
        this.gst = val;
      },
      password: function (val) {
        if (val.length === 6) { // 兑换
          axios.get(store.state.api + '/displace/displace', {
            params: {
              uid: this.user.uid,
              num: this.num,
              payPassword: val,
            }
          }).then(res => {
            this.show = false;
            this.showKeyboard = false;
            this.password = '';

            if (res.data.code == '200') {
              Toast({
                message: res.data.msg,
                position: 'bottom',
              });
              this.num = '';

              // 更新糖果
              this.updateCandy();
            } else {
              Toast({
                message: res.data.msg,
                position: 'bottom',
              });
            }
          }).catch(error => {
            Toast({
              message: '系统繁忙',
              position: 'bottom',
            });
          });
        }
      }
    },
    mounted: function() {
      // 计算最大兑换数
      this.max = parseInt(this.user.m_candy);
    },
    destroyed: function () {
      // 处理页面按回退键时页面空白的问题
      store.state.mine.showPopup = false;
    },
  }
</script>

<style scoped>
  .navbar {
    background-color: #545c80;
  }
  .right-text {
    color: #f7f8fa;
  }
  .title {
    color: #969799;
    font-size: 14px;
    text-align: center;
  }
  .label {
    margin-top: 4px;
    color: #323233;
    font-size: 24px;
    text-align: center;
  }
  .icon {
    text-align: center;
    color: #969799;
    line-height: 62px;
    font-size: 24px;
    height: 52px;
  }
  .btn {
    border: none;
  }
  .password-input {
    margin-bottom: 20px;
  }
  .keyboard {
    z-index: 3000;
  }
  .popup {
    width: 100%;
    height: 100%;
    background-color: #f7f8fa;
  }
</style>
